package com.rongshu.view.userInfo.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.rongshu.R;
import com.rongshu.utils.DateUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.userInfo.entity.SignDayResponse;
import com.rongshu.view.userInfo.entity.SignListResponse;
import com.rongshu.view.userInfo.iview.ISignView;
import com.rongshu.view.userInfo.presenter.SignPresenter;
import com.rongshu.widget.calendar.BanyanCalendarView;
import com.utils.DensityUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * created by zhengweis on 2019/2/19.
 * description：
 */
@SuppressLint("SetTextI18n")
public class SignActivity extends BaseActivity<SignPresenter> implements ISignView {

    @BindView(R.id.head_content)
    RelativeLayout head_content;
    @BindView(R.id.integral_tv)
    TextView integralTv;
    @BindView(R.id.sign_state)
    TextView signState;
    @BindView(R.id.sign_days)
    TextView signDays;
    @BindView(R.id.current_date)
    TextView currentDate;
    @BindView(R.id.calendarView)
    CalendarView calendarView;
    @BindView(R.id.supple_sign_card_num)
    TextView suppleSignCardNum;
    @BindView(R.id.supple_sign_num)
    TextView suppleSignNum;
    @BindView(R.id.sign_layout)
    RelativeLayout signLayout;
    @BindView(R.id.supple_sign)
    TextView suppleSign;
    @BindView(R.id.left_line)
    View leftLine;
    @BindView(R.id.right_line)
    View rightLine;
    //签到的标记
    private Map<String, Calendar> signedMap = new HashMap<>();
    //今天的日期
    private int currentYear;
    private int currentMonth;
    private int currentDay;
    //日历选中的日期
    private int suppleYear;
    private int suppleMonth;
    private int suppleDay;
    private String suppleScheme;
    //记录点击选中的日期
    private Calendar selectedCalendar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hintTitleBar();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_sign;
    }

    @Override
    protected void initView() {
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        currentYear = calendar.get(java.util.Calendar.YEAR);
        currentMonth = calendar.get(java.util.Calendar.MONTH) + 1;
        currentDay = calendar.get(java.util.Calendar.DAY_OF_MONTH);
        currentDate.setText(currentYear + "-" + currentMonth);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) head_content.getLayoutParams();
        layoutParams.topMargin = DensityUtil.getStateBar(this);
        head_content.setLayoutParams(layoutParams);
        //设置日历不可滚动
        calendarView.setMonthViewScrollable(false);
        //设置周view颜色
        calendarView.setWeeColor(ContextCompat.getColor(this, R.color.white),
                ContextCompat.getColor(this, R.color.color_4a4a4a));
        signLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int top = signLayout.getTop();
                RelativeLayout.LayoutParams leftLineLayoutParams = (RelativeLayout.LayoutParams) leftLine.getLayoutParams();
                leftLineLayoutParams.topMargin = top - leftLine.getHeight() / 3 * 2;
                leftLine.setLayoutParams(leftLineLayoutParams);
                RelativeLayout.LayoutParams rightLineLayoutParams = (RelativeLayout.LayoutParams) rightLine.getLayoutParams();
                rightLineLayoutParams.topMargin = top - leftLine.getHeight() / 3 * 2;
                rightLine.setLayoutParams(rightLineLayoutParams);

            }
        });
        calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                //已签到日期存在选中日期 return
                if (signedMap != null) {
                    int year = calendar.getYear();
                    int month = calendar.getMonth();
                    int day = calendar.getDay();
                    if (signedMap.containsKey(getSchemeCalendar(year, month, day, BanyanCalendarView.SELECTED).toString())
                            || signedMap.containsKey(getSchemeCalendar(year, month, day, BanyanCalendarView.SELECTED_SIGN).toString())) {
                        return;
                    }
                }
                //如果选中的日期》=今天 return
                if (calendar.getDay() >= currentDay) {
                    return;
                }
                //移除上次选中日期
                if (selectedCalendar != null) {
                    int year = selectedCalendar.getYear();
                    int month = selectedCalendar.getMonth();
                    int day = selectedCalendar.getDay();
                    if (signedMap.containsKey(getSchemeCalendar(year, month, day, BanyanCalendarView.SELECTED).toString())) {
                        signedMap.remove(getSchemeCalendar(year, month, day, BanyanCalendarView.SELECTED).toString());
                    }
                    if (signedMap.containsKey(getSchemeCalendar(year, month, day, BanyanCalendarView.SELECTED_SIGN).toString())) {
                        signedMap.remove(getSchemeCalendar(year, month, day, BanyanCalendarView.SELECTED_SIGN).toString());
                    }
                }
                //将选中日期加入map，并更新日历状态
                selectedCalendar = calendar;
                int year = selectedCalendar.getYear();
                int month = selectedCalendar.getMonth();
                int day = selectedCalendar.getDay();
                int cardNum = Integer.parseInt(suppleSignCardNum.getText().toString());
                String selectMark = cardNum > 0 ? BanyanCalendarView.SELECTED_SIGN : BanyanCalendarView.SELECTED;
                signedMap.put(getSchemeCalendar(year, month, day, selectMark).toString(),
                        getSchemeCalendar(year, month, day, selectMark));
                calendarView.setSchemeDate(signedMap);
            }
        });
    }

    @Override
    protected void initData() {
        setPresenter(new SignPresenter(this), this);
        showLoading(true);
        presenter.getSignMsg();
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        currentYear = calendar.get(java.util.Calendar.YEAR);
        currentMonth = calendar.get(java.util.Calendar.MONTH) + 1;
        currentDay = calendar.get(java.util.Calendar.DAY_OF_MONTH);
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @OnClick({R.id.head_left, R.id.supple_sign})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_left:
                finish();
                break;
            case R.id.supple_sign:
                Calendar suppleCalendar = calendarView.getSelectedCalendar();
                suppleYear = suppleCalendar.getYear();
                suppleMonth = suppleCalendar.getMonth();
                suppleDay = suppleCalendar.getDay();
                suppleScheme = suppleCalendar.getScheme();
                if (signedMap.containsKey(getSchemeCalendar(suppleYear, suppleMonth, suppleDay, BanyanCalendarView.SIGN).toString()) && suppleScheme.equals(BanyanCalendarView.SIGN)) {
                    toast("该日期已签到");
                } else {
                    showLoading(true);
                    presenter.getSignIn(2, suppleYear + "-" + suppleMonth + "-" + suppleDay);
                }
                break;
        }
    }

    private Calendar getSchemeCalendar(int year, int month, int day, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setScheme(text);
        return calendar;
    }

    @Override
    public void bindView(SignListResponse response) {
        List<SignListResponse.ResponseBean.ListBean> list = response.getResponse().getList();
        for (SignListResponse.ResponseBean.ListBean bean : list) {
            String signInDate = bean.getSignInDate();
            Date date = DateUtils.parseDate(DateUtils.YYYY_MM_DD_HH_MM_SS, signInDate);
            int year = Integer.valueOf(DateUtils.formatDate("yyyy", date));
            int month = Integer.valueOf(DateUtils.formatDate("MM", date));
            int day = Integer.valueOf(DateUtils.formatDate("dd", date));
            signedMap.put(getSchemeCalendar(year, month, day, BanyanCalendarView.SIGN).toString(),
                    getSchemeCalendar(year, month, day, BanyanCalendarView.SIGN));
        }
        //日历状态
        calendarView.setSchemeDate(signedMap);
        //总积分
        integralTv.setText(String.valueOf(response.getResponse().getSumFraction()));
        //联系签到次数 + 今日获得积分数
        signDays.setText("已经连续签到 " + response.getResponse().getSigninDays() + " 天，"
                + "今日签到获取 " + response.getResponse().getFraction() + " 积分");
        //补签卡数量
        suppleSignCardNum.setText(String.valueOf(response.getResponse().getFillSignCount()));
        //补签次数
        suppleSignNum.setText(String.valueOf(response.getResponse().getFillSignCiShu()));
        //补签按钮状态
        suppleSign.setBackgroundResource(response.getResponse().getFillSignCount() == 0 ?
                R.drawable.shape_base_bottom_round_gray : R.drawable.shape_base_bottom_round_green);
        suppleSign.setClickable(response.getResponse().getFillSignCount() != 0);
        /**
         * 对比接口返回的数据，如果今天未进行签到，则自动进行签到
         */
        if (!signedMap.containsKey(getSchemeCalendar(currentYear, currentMonth, currentDay, BanyanCalendarView.SIGN).toString())) {
            presenter.getSignIn(0, currentYear + "-" + currentMonth + "-" + currentDay);
        } else {
            showLoading(false);
        }
    }

    /**
     * 签到成功
     */
    @Override
    public void signSuccess(SignDayResponse response) {
        signedMap.put(getSchemeCalendar(currentYear, currentMonth, currentDay, BanyanCalendarView.SIGN).toString(),
                getSchemeCalendar(currentYear, currentMonth, currentDay, BanyanCalendarView.SIGN));
        calendarView.setSchemeDate(signedMap);
        //总积分
        integralTv.setText(String.valueOf(response.getResponse().getSumFraction()));
        //联系签到次数 + 今日获得积分数
        signDays.setText("已经连续签到 " + response.getResponse().getSigninDays() + " 天，"
                + "今日签到获取 " + response.getResponse().getFraction() + " 积分");
        //补签卡数量
        suppleSignCardNum.setText(String.valueOf(response.getResponse().getFillSignCount()));
        showLoading(false);
        presenter.showDialog(response.getResponse().getFraction());
    }

    /**
     * 补签成功
     */
    @Override
    public void suppleSignSuccess(SignDayResponse response) {
        signedMap.put(getSchemeCalendar(suppleYear, suppleMonth, suppleDay, BanyanCalendarView.SIGN).toString(),
                getSchemeCalendar(suppleYear, suppleMonth, suppleDay, BanyanCalendarView.SIGN));
        calendarView.setSchemeDate(signedMap);
        /**
         * 补签只计算补签卡数量/补签次数
         */
        //补签卡数量
        String signCount = suppleSignCardNum.getText().toString();
        int sign = Integer.valueOf(signCount);
        suppleSignCardNum.setText(sign - 1 + "");
        //补签次数
        String suppleCount = suppleSignNum.getText().toString();
        int supple = Integer.valueOf(suppleCount);
        suppleSignNum.setText(supple + 1 + "");
        showLoading(false);
    }

    @Override
    public void faild() {
        showLoading(false);
    }
}
